<?php

/**
 * 代理商中心
 */

namespace app\home\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use Helpers;

class Base extends Controller
{

    public $b_id;
    public $type;

    public function _initialize()
    {
        //处理登录
        $this->isLogin();
        //导航
        $request = \think\Request::instance();
        $action = $request->action();
        if($action == 'employeeAdd' || $action == 'updemployee'){
            $action = 'employeelist';
        }
        $agent_info = Session::get('agent_info');
        $this->b_id = $agent_info['id'];
        $this->type = $agent_info['type'];
        $this->assign('type', $this->type);
        $this->assign('action', $action);
    }

    //验证是否登录
    public function isLogin()
    {
        $agent_info = Session::get('agent_info');
        if (empty($agent_info)) {
            $this->redirect('Login/index');
        }
        $this->assign('agent_info', $agent_info);
    }

    //该用户基本信息
    public function index()
    {
        if ($this->type == 0) {
            $data = Db::name('education_business')->where('b_id', $this->b_id)->find();
            return $this->fetch('base', ['data' => $data]);
        } else {
            $data = Db::name('education_business_employee')->where('b_id', $this->b_id)->find();
            $login_data = Db::name('education_business_login')->where('id', $this->b_id)->find();
            return $this->fetch('education_business_employee', ['employee_data' => $data, 'login_data' => $login_data]);
        }
    }

    //修改基本信息
    public function saveDetail()
    {
        $request = Request::instance();
        $post = $request->post();
        if (empty($post['id'])) {
            $this->error('参数不对', 'home/base/index');
        }
        $data = [
            'company_name' => $post['company_name'],
            'organization_code' => $post['organization_code'],
            'user_name' => $post['user_name'],
            'phone' => $post['phone'],
            'mobile' => $post['mobile'],
            'email' => $post['email'],
            'company_address' => $post['company_address'],
            'taxpayer_type' => $post['taxpayer_type'],
            'tax_id' => $post['tax_id'],
            'leal_person' => $post['leal_person'],
            'id_type' => $post['id_type'],
            'id_num' => $post['id_num'],
            'business_scope' => $post['business_scope'],
            'bank_name' => $post['bank_name'],
            'bankaccount_number' => $post['bankaccount_number'],
            'bankaccount_holder' => $post['bankaccount_holder'],
        ];

        $res = Db::table('h_education_business')->where('id', $post['id'])->update($data);
        if ($res == 0) {
            // $this->success('信息未发生改变', 'home/base/index');
            echo json_encode(['code' => '1004', 'msg' => '信息未发生改变']);
        } else {
            echo json_encode(['code' => '1003', 'msg' => '修改已保存']);
            // $this->error('修改已保存', 'home/base/index');
        }
    }
    public function employeeList()
    {
        // $data['info'] = Db::name('education_business_employee')->where('p_id', $this->b_id)->order('b_id desc')->select();
        $data = Db::name('education_business_employee')->where('p_id', $this->b_id)->paginate(1);
        return $this->fetch('employeelist', ['data' => $data]);
    }

    public function employeeAdd()
    {   
        return view('employeeadd');
    }

    public function ass()
    {
        $this->success('添加成功', 'home/base/employeelist');
    }

    public function doemployeeAdd()
    {

        $request = Request::instance();
        $post = $request->post();
        // console.log($post);die;
        Db::startTrans();
        try {

            $login_data = [
                'username' => strval($post['employee_loginnum']),
                'pwd' => md5($post['employee_password']),
                'p_id' => $this->b_id,
                'type' => 1, //员工
                'status' => 1,
            ];

            // print_r($login_data);die;
            Db::name('education_business_login')->insert($login_data);
            $b_id = Db::name('education_business_login')->getLastInsID();

            $data = [
                'b_id' => intval($b_id),
                'employee_name' => $post['employee_name'],
                'employee_mobile' => $post['employee_mobile'],
                'p_id' => $this->b_id,
            ];
            Db::name('education_business_employee')->insert($data);
            Db::commit();
            //1001 添加成功
            echo json_encode(['code' => "1001", 'msg' => '添加成功']);
            // header("location: employeelist");
            // $this->success('添加成功','home/base/employeelist');
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
            // 回滚事务
            Db::rollback();
            //1002 添加失败
            echo json_encode(['code' => "1002", 'msg' => '添加失败']);
            // $this->error('添加失败', 'home/base/employeeAdd');
        }
    }

    public function delemployee()
    {
        $request = Request::instance();
        $get = $request->get();
        $b_id = $get['id'];

        // print_r($b_id);die;
        Db::startTrans();
        try {
            Db::name('education_business_login')->delete($b_id);
            Db::name('education_business_employee')->where('b_id', $b_id)->delete();
            Db::commit();
            header("location: employeelist");
            // $this->success('删除成功', 'home/base/employeelist');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }

    public function updemployee()
    {
        $request = Request::instance();
        $get = $request->get();
        $id = $get['id'];

        // print_r($id);die;
        $employee_data = Db::name('education_business_employee')
            ->where('b_id', $id)
            ->find();
        $login_data = Db::name('education_business_login')
            ->where('id', $id)
            ->find();
        // print_r($employee_data);
        //         print_r($login_data);die;
        return $this->fetch('updemployee', ['employee_data' => $employee_data, 'login_data' => $login_data]);
    }

    public function doUpdemployee()
    {
        $request = Request::instance();
        $post = $request->post();

        $url = 'home/base/employeeList';
        if ($this->type == 1) {
            $url = 'home/base/index';
        }

        if (empty($post)) {
            echo json_encode(['code'=>'1000','msg'=>'修改失败']);exit();
        }
        $login_data = Db::name('education_business_login')->where('username', $post['employee_loginnum'])->select();
        if (count($login_data) >= 2) {
            // $this->success('对不起，用户名已存在', 'home/base/employeeAdd');
            echo json_encode(['code'=>'1000','msg'=>'对不起，用户名已存在']);exit();
        }
        Db::startTrans();
        try {
            $login_data = [
                'username' => $post['employee_loginnum'],
                //'pwd' => md5($post['employee_password']),
            ];
            Db::name('education_business_login')->where('id', $post['b_id'])->update($login_data);
            $data = [
                'employee_name' => $post['employee_name'],
                'employee_mobile' => $post['employee_mobile'],
            ];
            Db::name('education_business_employee')->where('b_id', $post['b_id'])->update($data);
            Db::commit();
            echo json_encode(['code'=>'1001','msg'=>'修改成功']);exit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
            // 回滚事务
            Db::rollback();
            echo json_encode(['code'=>'1000','msg'=>'修改成功']);exit();
        }
        // $this->success('修改成功', $url);
    }

    public function productList()
    {
        $get = Request::instance()->get();

        $data = Db::name('education_business')->where('b_id=' . $this->b_id)->find();

        // print_r($data);die;
        if (isset($get['type_id'])) {
            $data = Db::name('education_virtualcard')->where('cart_type=' . $get['type_id'])->where('id', 'in', $data['card_batches'])
                ->paginate(5);
        } else {
            $get['type_id'] = 0;
            $data = Db::name('education_virtualcard')->where('id', 'in', $data['card_batches'])->paginate(2);

            // print_r($data);die;
        }

        return $this->fetch('productlist', ['data' => $data, 'get' => $get]);
    }
    /**
     * [clientList 客户列表]
     * @return [type] [description]
     */
    public function clientList()
    {
        $url = "https://zhssw100.zhssw.com/Msjtapi/users_list?tdsourcetag=s_pcqq_aiomsg";
        $data = curl($url);
        
        $grade = Db::name('education_grade_category')->order('sort asc')->select();
       
        return $this->fetch('clientlist', ['data' => $data['data'],'grade'=>$grade]);
    }

    public function clineconsumer()
    {
        $url = "https://zhssw100.zhssw.com/Msjtapi/users_list?tdsourcetag=s_pcqq_aiomsg";
        $data = curl($url);
        $grade = Db::name('education_grade_category')->order('sort asc')->select();
        return $this->fetch('clineconsumer', ['data' => $data['data'],'grade'=>$grade]);
    }

//业绩提成
    public function performance()
    {
//print_r($data);
        // $data1 = Db::name('user')->select();
        // $count = count($data1);
        // $data = Db::name('user')->paginate(1,$count);
        //
        $url = "https://zhssw100.zhssw.com/Msjtapi/users_list?tdsourcetag=s_pcqq_aiomsg";
        $data = curl($url);
        return $this->fetch('performance', ['data' => $data['data']]);
    }

//分销管理方法

    public function distribution()
    {
        $data = Db::name('education_business_url')->where('b_id', $this->b_id)->find();
        $business_data = Db::name('education_business')->where('b_id', $this->b_id)->find();
        return view('distribution', ['data' => $data, 'business_data' => $business_data]);
    }

//提现管理方法
    public function withdraw()
    {

        $data = Db::name('education_withdraw')->where('proxy_id', $this->b_id)->select();
        $arr = Db::name('education_business')->where('b_id', $this->b_id)->order('id desc')->find();

        // print_r($data);die;

        return $this->fetch('withdraw', ['data' => $data, 'arr' => $arr]);
    }

//提现申请提交
    public function apply()
    {
        $request = Request::instance();
        $post = $request->post();
        if (!empty($post)) {
            $withdraw_data = date("Y-m-d H:i:s", time());
            //print_r($post);die;
            $data = [
                'withdraw_amount' => $post['withdraw_amount'],
                'bank_id' => $post['bank_id'],
                'bank_name' => $post['bank_name'],
                'bank_head' => $post['bank_head'],
                'proxy_id' => $this->b_id,
                'withdraw_data' => $withdraw_data];

            // print_r($data);die;

            $info = Db::name('education_business')->where('b_id', $this->b_id)->find();

            $now_money = $info['bankaccount_balance'] - $post['withdraw_amount'];

            Db::name('education_business')->where('b_id', $this->b_id)->update(['bankaccount_balance' => $now_money]);

            $res = Db::name('education_withdraw')->insert($data);
            if ($res != 0) {
                return json_encode(['code' => '1005', 'msg' => '申请已提交']);
                // $this->success('申请已提交', 'home/base/withdraw');
            } else {
                return json_encode(['code' => '1006', 'msg' => '提交失败']);
                // $this->error('提交失败', 'home/base/withdraw');
            }
        }
        $business_data = Db::name('education_business')->where('b_id', $this->b_id)->find();
        return $this->fetch('withdraw_apply', ['arr' => $business_data]);
    }

//修改密码
    public function updatePwd()
    {
        return view('updatepwd');
    }

//执行密码修改
    public function doUpdatepwd()
    {
        $request = Request::instance();
        $post = $request->post();
//print_r($post);
        $data = $data = Db::name('education_business_login')->where('id', $this->b_id)->find();
        if (md5($post['pwd']) == $data['pwd']) {
            if (md5($post['newpwd']) == md5($post['surepwd'])) {
                $arr = ['pwd' => md5($post['newpwd'])];
                $res = Db::name('education_business_login')->where('id', $this->b_id)
                    ->update($arr);
                if ($res != 0) {
                    $this->success('修改成功', 'home/base/updatepwd');
                } else {
                    $this->error('', 'home/base/updatepwd');
                }
            } else {
                $this->error('您的新密码和确认密码不一致', 'home/base/updatepwd');
            }
        } else {
            $this->error('您输入的原密码不正确!', 'home/base/updatepwd');
        }
    }

}
